<template>
  <view class="container">
    <Loading :show="isLoading" />
    
    <!-- 地图容器 -->
    <map
      class="map"
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
      :scale="16"
      show-location
      @markertap="handleMarkerTap"
    ></map>

    <!-- 刷新按钮 -->
    <view class="refresh-btn" @click="handleRefresh">
      <text class="refresh-icon">↻</text>
    </view>

    <!-- 设备列表 -->
    <view class="device-list" v-if="devices.length > 0">
      <view class="list-header">
        <text class="title">附近有货的售货机</text>
        <text class="count">({{ devices.length }})</text>
      </view>
      
      <scroll-view scroll-y class="list-content">
        <view 
          v-for="device in devices" 
          :key="device.id"
          class="device-item"
          :class="{ active: selectedDevice?.id === device.id }"
          @click="selectDevice(device)"
        >
          <view class="device-info">
            <text class="device-name">{{ device.name }}</text>
            <text class="device-address">{{ device.address }}</text>
            <view class="device-meta">
              <text class="stock">库存: {{ device.stock }}</text>
              <text class="distance">{{ device.distance }}km</text>
            </view>
          </view>
          <view class="device-actions">
            <button class="navigate-btn" @click.stop="navigateToDevice(device)">导航</button>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 无设备提示 -->
    <view v-else class="no-device">
      <image src="/static/empty.png" mode="aspectFit" class="empty-image" />
      <text>附近暂无有货的售货机</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import Loading from '@/components/Loading.vue';
import { getDeviceWithStock } from '@/api/device';
import * as mapApi from '@/api/map';
import { getDeviceDetail } from '@/api/device';

interface Device {
  id: number;
  name: string;
  latitude: number;
  longitude: number;
  address: string;
  stock: number;
  distance: number;
}

const isLoading = ref(false);
const devices = ref<Device[]>([]);
const selectedDevice = ref<Device | null>(null);
const latitude = ref(39.908823);
const longitude = ref(116.397470);
const markers = ref<any[]>([]);
const productId = ref<number>(0);
const mapContext = ref<any>(null);

// 检查位置权限
const checkLocationPermission = () => {
  return new Promise((resolve, reject) => {
    uni.authorize({
      scope: 'scope.userLocation',
      success: () => {
        resolve(true);
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '需要获取您的位置信息，是否授权？',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.userLocation']) {
                    resolve(true);
                  } else {
                    reject(new Error('用户拒绝授权位置信息'));
                  }
                },
                fail: () => {
                  reject(new Error('打开设置页面失败'));
                }
              });
            } else {
              reject(new Error('用户拒绝授权位置信息'));
            }
          }
        });
      }
    });
  });
};

// 获取当前位置
const getCurrentLocation = async () => {
  try {
    // 先检查权限
    await checkLocationPermission();
    
    // 显示加载提示
    uni.showLoading({
      title: '定位中...'
    });

    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          latitude.value = res.latitude;
          longitude.value = res.longitude;
          resolve(res);
        },
        fail: (err) => {
          console.error('获取位置失败：', err);
          reject(err);
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    });
  } catch (error) {
    console.error('位置权限检查失败：', error);
    uni.showToast({
      title: error.message || "获取位置失败",
      icon: "error",
      duration: 2000
    });
    throw error;
  }
};

// 计算两点之间的距离（使用高德地图的距离计算）
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
  if (!lat1 || !lon1 || !lat2 || !lon2) {
    console.log('距离计算参数无效：', { lat1, lon1, lat2, lon2 });
    return 0;
  }
  
  const R = 6378137; // 地球半径，单位米
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  
  // 转换为公里，保留一位小数
  const distanceInKm = Number((distance / 1000).toFixed(1));
  console.log('距离计算结果：', {
    from: { lat: lat1, lon: lon1 },
    to: { lat: lat2, lon: lon2 },
    distance: distanceInKm
  });
  return distanceInKm;
};

// 获取附近设备
const fetchNearbyDevices = async () => {
  try {
    isLoading.value = true;
    
    // 确保当前位置已获取
    if (!latitude.value || !longitude.value) {
      await getCurrentLocation();
    }

    console.log('当前位置：', {
      latitude: latitude.value,
      longitude: longitude.value
    });

    // 搜索周边设备
    const result = await mapApi.searchAround(longitude.value, latitude.value, '', 5);
    if (result.data) {
      // 获取每个设备的详细信息
      const deviceDetails = await Promise.all(
        result.data.map(async (device) => {
          const detail = await getDeviceDetail(device.deviceId, 1);
          return {
            ...device,
            ...detail
          };
        })
      );

      // 过滤出有库存的设备
      const devicesWithStock = await Promise.all(
        deviceDetails.map(async (device) => {
          const stockRes = await getDeviceWithStock(productId.value);
          // 找到对应设备的库存信息
          const stockInfo = stockRes.data?.find((stock: any) => stock.deviceId == device.deviceId);
          return {
            ...device,
            hasStock: !!stockInfo,
            stockQuantity: stockInfo?.stockQuantity || 0
          };
        })
      );

      devices.value = devicesWithStock
        .filter(device => device.hasStock)
        .map(device => {
          const deviceLat = Number(device.location?.latitude || device.location?.lat);
          const deviceLon = Number(device.location?.longitude || device.location?.lon);
          
          console.log('设备位置：', {
            deviceId: device.deviceId,
            latitude: deviceLat,
            longitude: deviceLon
          });

          // 计算距离
          const distance = calculateDistance(
            latitude.value,
            longitude.value,
            deviceLat,
            deviceLon
          );

          return {
            id: device.id || device.deviceId,
            name: device.deviceName || '自助售货机',
            latitude: deviceLat,
            longitude: deviceLon,
            address: device.location?.address || device.siteName || '',
            stock: device.stockQuantity || 0,
            distance: distance
          };
        });

      // 按距离排序
      devices.value.sort((a, b) => a.distance - b.distance);
      
      console.log('处理后的设备列表：', devices.value);
      
      // 更新地图标记
      initMarkers();
      
      // 如果有设备，默认选中第一个
      if (devices.value.length > 0) {
        selectDevice(devices.value[0]);
      } else {
        uni.showToast({
          title: '附近暂无有货的售货机',
          icon: 'none',
          duration: 2000
        });
      }
    }
  } catch (error) {
    console.error('获取附近设备失败：', error);
    uni.showToast({
      title: '获取附近设备失败',
      icon: 'none',
      duration: 2000
    });
  } finally {
    isLoading.value = false;
  }
};

// 初始化地图标记
const initMarkers = () => {
  markers.value = devices.value.map(device => ({
    id: device.id,
    latitude: device.latitude,
    longitude: device.longitude,
    title: device.name,
    iconPath: '/static/marker.png',
    width: 32,
    height: 32,
    callout: {
      content: `${device.name}\n库存: ${device.stock}`,
      color: '#000000',
      fontSize: 14,
      borderRadius: 4,
      padding: 8,
      display: 'ALWAYS'
    }
  }));

  // 如果有设备，调整地图视野以包含所有标记
  if (markers.value.length > 0) {
    mapContext.value = uni.createMapContext('map');
    mapContext.value.includePoints({
      points: markers.value.map(marker => ({
        latitude: marker.latitude,
        longitude: marker.longitude
      })),
      padding: [50]
    });
  }
};

// 处理标记点击
const handleMarkerTap = (e: any) => {
  const device = devices.value.find(d => d.id === e.markerId);
  if (device) {
    selectDevice(device);
  }
};

// 选择设备
const selectDevice = (device: Device) => {
  selectedDevice.value = device;
  // 移动地图到选中设备的位置
  mapContext.value?.moveToLocation({
    latitude: device.latitude,
    longitude: device.longitude
  });
};

// 导航到设备
const navigateToDevice = (device: Device) => {
  if (!device.latitude || !device.longitude) {
    console.error('设备位置信息不完整：', device);
    uni.showToast({
      title: '设备位置信息不完整',
      icon: 'none',
      duration: 2000
    });
    return;
  }


  // 然后跳转到导航页面
  uni.navigateTo({
    url: `/pages/device/navigate?id=${device.id}`
  });
};

// 处理刷新
const handleRefresh = async () => {
  try {
    uni.showLoading({
      title: '刷新中...'
    });
    
    // 重新获取当前位置
    await getCurrentLocation();
    
    // 重新获取附近设备
    await fetchNearbyDevices();
    
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000
    });
  } catch (error) {
    console.error('刷新失败：', error);
    uni.showToast({
      title: '刷新失败',
      icon: 'error',
      duration: 2000
    });
  } finally {
    uni.hideLoading();
  }
};

// 页面加载
onLoad(async (options) => {
  try {
    isLoading.value = true;
    
    // 获取商品ID
    if (options?.productId) {
      productId.value = Number(options.productId);
    }
    
    // 获取当前位置
    await getCurrentLocation();
    
    // 获取附近设备
    await fetchNearbyDevices();
  } catch (error) {
    console.error('初始化失败：', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
      duration: 2000
    });
  } finally {
    isLoading.value = false;
  }
});
</script>

<style>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.map {
  width: 100%;
  height: 100%;
}

.device-list {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 24rpx;
  max-height: 60vh;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.list-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.count {
  font-size: 28rpx;
  color: #999;
  margin-left: 12rpx;
}

.list-content {
  max-height: calc(60vh - 100rpx);
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  transition: all 0.3s ease;
}

.device-item.active {
  background-color: #e6f7ff;
  border: 2rpx solid #1890ff;
}

.device-info {
  flex: 1;
  margin-right: 24rpx;
}

.device-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.device-address {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.device-meta {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.stock {
  font-size: 24rpx;
  color: #ff4d4f;
  background-color: #fff1f0;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.distance {
  font-size: 24rpx;
  color: #1890ff;
  background-color: #e6f7ff;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.device-actions {
  display: flex;
  align-items: center;
}

.navigate-btn {
  padding: 12rpx 24rpx;
  background-color: #1890ff;
  color: #fff;
  font-size: 24rpx;
  border-radius: 8rpx;
  border: none;
  line-height: 1.5;
}

.navigate-btn:active {
  opacity: 0.8;
}

.no-device {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 24rpx;
}

.refresh-btn {
  position: absolute;
  top: 40rpx;
  right: 40rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.refresh-btn:active {
  opacity: 0.8;
}

.refresh-icon {
  font-size: 40rpx;
  color: #1890ff;
}
</style>